package com.moco.launcher.adapter;

import android.database.DataSetObserver;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import com.oazon.common.Logger;

public class CycleViewAdapter extends PagerAdapter {
	private static final String TAG = "CycleViewAdapter";
	
	private PagerAdapter mAdapter;

	public CycleViewAdapter(PagerAdapter adapter) {
		adapter.registerDataSetObserver(new DataSetObserver() {
			@Override
			public void onChanged() {
				notifyDataSetChanged();
			}

			@Override
			public void onInvalidated() {
				notifyDataSetChanged();
			}
		});
		
		mAdapter = adapter;
	}
	
	@Override
	public int getCount() {
		if (mAdapter.getCount() > 0)
			return mAdapter.getCount() + 2;
		
		return 0;
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return mAdapter.isViewFromObject(arg0, arg1);
	}

	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		Logger.d(TAG, "instantiateItem  Cyc==" + position);
		if (position == 0) {
			position = Integer.MIN_VALUE;
		} else if (position == mAdapter.getCount() + 1) {
			position = Integer.MAX_VALUE;
		} else {
			position -= 1;
		}
		
		return mAdapter.instantiateItem(container, position);
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		if (position == 0) {
			position = mAdapter.getCount() - 1;
		} else if (position == mAdapter.getCount() + 1) {
			position = 0;
		} else {
			position -= 1;
		}
		mAdapter.destroyItem(container, position, object);
	}

	@Override
	public int getItemPosition(Object object) {
		return super.getItemPosition(object);
	}

}
